package com.yssoft.service.inspection;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.yssoft.entity.core.TCode;
import com.yssoft.entity.inspection.TInspReport;
import com.yssoft.entity.inspection.TInspReportAtt;
import com.yssoft.entity.inspection.TInspReportDetail;
import com.yssoft.entity.inventory.TInstockApply;
import com.yssoft.entity.purchase.TPurchaseAtt;
import com.yssoft.mapper.core.TCodeMapper;
import com.yssoft.mapper.inspection.TInspReportAttMapper;
import com.yssoft.mapper.inspection.TInspReportDetailMapper;
import com.yssoft.mapper.inspection.TInspReportMapper;
import com.yssoft.mapper.inspection.TInspStandardEntMapper;
import com.yssoft.mapper.inventory.TInstockApplyMapper;
import com.yssoft.utils.AppUserHelper;
import com.yssoft.utils.AppUtil;
import com.yssoft.utils.UploadFile;

/**
 * @author 戈超
 * @time 2018/5/21 上午 09:31 @ 检验管理service
 */
@Service
public class InspReportService {

	@Resource
	private TInstockApplyMapper tInstockApplyMapper;
	@Resource
	private TCodeMapper tCodeMapper;
	@Resource
	private TInspStandardEntMapper tInspStandardEntMapper;
	@Resource
	private TInspReportAttMapper tInspReportAttMapper;
	@Resource
	private TInspReportMapper tInspReportMapper;
	@Resource
	private TInspReportDetailMapper tInspReportDetailMapper;

	/**
	 * 入库申请单列表查询
	 * @author 戈超
	 * @param currentPage
	 * @param pageSize
	 * @param stat
	 * @param pType
	 * @param request
	 * @return
	 */
	public List<Map<String, Object>> queryInstockApplyList(Integer currentPage, Integer pageSize, String inspStat,
			String pType, HttpServletRequest request) {
		/*查询条件整理*/
		Map<String, Object> param = new HashMap<>();
		param.put("tEid", AppUserHelper.getCurrentCompanyId(request));
		param.put("deleteFlag", "0");
		param.put("inspStat", inspStat);
		if(pType != null){
			switch (pType) {
			case "1":
				param.put("pType", pType);
				break;
			case "2":
				param.put("pType", pType);
				break;
			case "3":
				param.put("classify", "rawClassify");
				break;
			case "4":
				param.put("classify", "packagingClassify");
				break;
			case "5":
				param.put("classify", "accessoriesClassify");
				break;
			case "6":
				param.put("classify", "additiveClassify");
				break;
			}
		}
		if(currentPage != null && pageSize != null){
			/*分页整理*/
			int start = (currentPage-1) * pageSize;
			int end = pageSize;
			param.put("start",start);
			param.put("end", end);
		}
		List<Map<String, Object>> list = tInstockApplyMapper.queryInstockApplyList(param);
		return list;
	}

	/**
	 * 查询产品分类列表
	 * @author 戈超
	 * @return
	 */
	public List<TCode> queryCodeList() {
		TCode code = new TCode();
		code.setDeleteFlag("0");
		code.setClassify("material");
		List<TCode> codeList = tCodeMapper.select(code);
		return codeList;
	}

	/**
	 * 查询检验项目列表
	 * @author 戈超
	 * @param request 
	 * @param standardName 
	 * @param pageSize 
	 * @param currentPage 
	 * @param pType 
	 * @param ids 
	 * @return
	 */
	public List<Map<String, Object>> queryStandardEntList(Integer currentPage, Integer pageSize, String standardName, String pType, String ids, String productId, HttpServletRequest request) {
		/*查询条件整理*/
		Map<String, Object> param = new HashMap<>();
		param.put("tEid", AppUserHelper.getCurrentCompanyId(request));
		param.put("deleteFlag", "0");
		param.put("standardName", standardName);
		if("3".equals(pType) || "4".equals(pType) || "5".equals(pType) || "6".equals(pType)){
			pType = "3";
		}
		param.put("pType", pType);
		param.put("productId", productId);
		if(ids != null && ids.length() > 0){
			String[] id = ids.split(",");
			param.put("inspIds", id);
		}
		
		if(currentPage != null && pageSize != null){
			/*分页整理*/
			int start = (currentPage-1) * pageSize;
			int end = pageSize;
			param.put("start",start);
			param.put("end", end);
		}
		
		List<Map<String,Object>> list = tInspStandardEntMapper.queryStandardEntList(param);
		return list;
	}

	/**
	 * 保存检验报告
	 * @author 戈超
	 * @param tInspReport
	 * @param tInspStaEId
	 * @param isUp
	 * @param inspValue
	 * @param request
	 * @param files
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Object uploadContract(TInspReport tInspReport, String[] tInspStaEId, String[] isUp, String[] inspValue, HttpServletRequest request,
			MultipartFile[] files) {
		//保存报告
		String code = "JY"+System.currentTimeMillis() + "";
		tInspReport.setCode(code);
		tInspReport.setDeleteFlag("0");
		tInspReport.setCreateTime(new Date());
		tInspReport.setCreatorName(AppUserHelper.getCurrentUserName(request));
		tInspReport.setCreatorId(AppUserHelper.getCurrentUserId(request));
		tInspReport.settEId(AppUserHelper.getCurrentCompanyId(request));
		if("1".equals(tInspReport.getInspType())){
			tInspReport.setInspOrg(null);
		}
		if("1".equals(tInspReport.getInspResult())){
			tInspReport.setOpMethod(null);
			tInspReport.setOpPerson(null);
			tInspReport.setOpTime(null);
		}
		int num = tInspReportMapper.insertSelective(tInspReport);
		if(num > 0){
			Integer id = tInspReport.getId();
			//保存详细
			if(tInspStaEId != null && tInspStaEId.length > 0){
				TInspReportDetail tInspReportDetail = new TInspReportDetail();
				tInspReportDetail.setDeleteFlag("0");
				tInspReportDetail.setCreateTime(new Date());
				tInspReportDetail.setCreatorName(AppUserHelper.getCurrentUserName(request));
				tInspReportDetail.setCreatorId(AppUserHelper.getCurrentUserId(request));
				for(int i = 0; i < tInspStaEId.length; i++){
					tInspReportDetail.setId(null);
					tInspReportDetail.settInspStaEId(Integer.parseInt(tInspStaEId[i]));
					tInspReportDetail.setIsUp(isUp[i]);
					tInspReportDetail.setInspValue(inspValue[i]);
					tInspReportDetail.settInspReportId(id);
					tInspReportDetailMapper.insertSelective(tInspReportDetail);
				}
			}
			//保存附件
			MultipartRequest mRequest=(MultipartRequest)request;
			Iterator<String> fileNames = mRequest.getFileNames();
			while(fileNames.hasNext()){
				MultipartFile file = mRequest.getFile(fileNames.next());
				Map<String,Object> urlMap = null;
                try {
                    urlMap = UploadFile.compressUploadedFile(file);
                } catch (Exception e) {
                    return AppUtil.returnMapJson("0", "上传图片失败" + e.getMessage(), null);
                }
               
                TInspReportAtt att = new TInspReportAtt();
                att.setUrl(urlMap.get("fileName")+"");
                att.setTurl(urlMap.get("thumbnails")+"");
                att.settInspReportId(id);
                att.setDeleteFlag("0");
                att.setCreateTime(new Date());
                att.setCreatorName(AppUserHelper.getCurrentUserName(request));
                att.setCreatorId(AppUserHelper.getCurrentUserId(request));
                tInspReportAttMapper.insertSelective(att);
			}
			return AppUtil.returnMapJson("1", "保存成功!", null);
		} else {
			return AppUtil.returnMapJson("0", "保存失败!", null);
		}
		
	}

	/**
	 * 检验报告确认完成
	 * @author 戈超
	 * @param instockId
	 * @param inspStat
	 */
	public void instockCompletion(Integer instockId, String inspStat) {
		//修改状态
		TInstockApply tInstockApply = new TInstockApply();
		tInstockApply.setId(instockId);
		tInstockApply.setInspStat(inspStat);
		tInstockApplyMapper.updateByPrimaryKeySelective(tInstockApply);
	}

	/**
	 * 查看检验报告
	 * @author 戈超
	 * @param instockId
	 * @return
	 */
	public List<Map<String,Object>> InspectionView(Integer instockId, HttpServletRequest request) {
		/*查询检验报告*/
		Map<String, Object> paramReport = new HashMap<>();
		paramReport.put("deleteFlag", "0");
		paramReport.put("tEId", AppUserHelper.getCurrentCompanyId(request));
		paramReport.put("instockAppId", instockId);
		List<Map<String,Object>> tInspReportList = tInspReportMapper.queryReportByPid(paramReport);
		for(Map<String,Object> report: tInspReportList){
			/*查询检验报告详细*/
			Map<String, Object> param = new HashMap<>();
			param.put("tInspReportId", report.get("id"));
			param.put("deleteFlag", "0");
			List<Map<String,Object>> detailList = tInspReportDetailMapper.queryInspReportDetail(param);
			report.put("tInspReportDetailList", detailList);
			/*查询检验报告附件*/
			TInspReportAtt tInspReportAtt = new TInspReportAtt();
			tInspReportAtt.settInspReportId(Integer.parseInt(report.get("id").toString()));
			tInspReportAtt.setDeleteFlag("0");
			List<TInspReportAtt> attList = tInspReportAttMapper.select(tInspReportAtt);
			report.put("tInspReportAttList", attList);
		}
		return tInspReportList;
	}
}
